// 实现懒加载
const lazy = (Vue) => {
    Vue.directive('gp8-lazy', {
        // 只在绑定后执行一次
        bind (el, binding) {
            el.handler =  judgeDistance.bind(el);
            el.setAttribute('data-src', binding.value);
            el.handler();
        },
        // 只要出现在 dom 中一次就执行一次
        inserted (el) {
            window.addEventListener('scroll', el.handler);
        },
        // 销毁的时候执行
        unbind () {
            window.removeEventListener('scroll', el.handler);
        }
    })

    function judgeDistance() {
        let page = this.offsetTop;
        let scrollTop = document.documentElement.scrollTo;
        let clientHeight = document.documentElement.clientHeight;
        let distance = 50;

        if ( page - (scrollTop + clientHeight + distance) && !this.src ) {
            this.src = this.getAttribute('data-src');
        }

    }
}

export default lazy;
